﻿using Enyim.Caching.Configuration;
using RpcCacheClient.Interface;
using RpcCentral.Common;
using RpcCentral.DAL;
using RpcCentral.Model;
using RpcCentral.Model.DB;
using RpcHelper;
using RpcModel.Server;

namespace RpcCentral.Collect.Collect
{
    internal class RpcServerStateCollect : IRpcServerStateCollect
    {
        private IServerRunStateDAL _ServerRunState;
        private ICacheController _Cache;
        public RpcServerStateCollect(IServerRunStateDAL serverRunState, ICacheController cache)
        {
            _ServerRunState = serverRunState;
            _Cache = cache;
        }

        public RunEnvironment GetEnvironments(long serverId)
        {
            string key = "Environment_" + serverId;
            if(_Cache.TryGet(key,out RunEnvironment env))
            {
                return env;
            }
            env = _ServerRunState.GetEnvironments(serverId);
            if (env != null)
            {
                _Cache.Set(key, env, new TimeSpan(1, 0, 0, 0));
            }
            return env;
        }
        private void _Clear(long serverId)
        {
            string key = "Environment_" + serverId;
            _Cache.Remove(key);
        }
        private void _AddRunState(long id, ProcessDatum datum)
        {
            ServerRunStateModel add = datum.ConvertMap<ProcessDatum, ServerRunStateModel>();
            add.ServerId = id;
            add.SyncTime = DateTime.Now;
            _ServerRunState.AddRunState(add);
        }
        private void _SetRunState(long id, ProcessDatum datum)
        {
            if (!_ServerRunState.UpdateRunState(id, datum.ConvertMap<ProcessDatum, ServerRunStateSet>()))
            {
                throw new ErrorException("rpc.sever.runstate.set.error");
            }
            _Clear(id);
        }
        public void SyncRunState(long id, ProcessDatum datum)
        {
            if (!_ServerRunState.CheckIsReg(id))
            {
                _AddRunState(id, datum);
                return;
            }
            _SetRunState(id, datum);
        }
    }
}
